/**
 * 
 */
package pt.mleiria.sound;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;

/**
 * @author NB13712
 *
 */
public class TextToSpeech implements SoundBehaviour{
	private static final Logger LOG = Logger.getLogger(TextToSpeech.class);
	private final String message;
	private boolean isSoundFile = true;
		
	public TextToSpeech(final String message) {
		this.message = message;
	}
	
	public void setSoundFile(boolean isSoundFile) {
		this.isSoundFile = isSoundFile;
	}



	public void makeSound() {
		LOG.info("makeSound from TextToSpeech...");
		if(true)return;
		final Runtime rt = Runtime.getRuntime();
        try {
			//Process proc = rt.exec("mpg321 /home/manuel/domus/LebaneseBlonde.mp3");
        	Process proc;
        	if(isSoundFile){
        		proc = rt.exec("espeak -v en-en -s 80 -f " + createTempFile());
        	}else{
        		proc = rt.exec("espeak -v en-en -s 80 " + message);
        	}
			final InputStream stderr = proc.getErrorStream();
            final InputStreamReader isr = new InputStreamReader(stderr);
            final BufferedReader br = new BufferedReader(isr);
            String line = null;
            while((line = br.readLine()) != null){
                LOG.info(line);
            }
            int exitVal = proc.waitFor();
            LOG.info("exitVal:" + exitVal);
		} catch (Exception e) {
			LOG.fatal(e.getMessage());
			e.printStackTrace();
		}
	}

	private String createTempFile() throws FileNotFoundException, UnsupportedEncodingException{
		final String file = "D:/SkyDrive/DomusProject/soundLib/tempFile.txt";
		final PrintWriter writer = new PrintWriter(file, "UTF-8");
		writer.println(message);
		writer.close();
		return file;
	}

}
